package com.hczt.fire.server.backend.sys.controller;

import com.hczt.fire.entity.sys.SysRole;
import com.hczt.fire.entity.validator.group.Create;
import com.hczt.fire.entity.validator.group.Update;
import com.hczt.fire.framework.jpa.repository.support.PagedQuery;
import com.hczt.fire.server.backend.sys.service.SysRoleService;
import com.hczt.fire.server.common.Constant;
import com.hczt.fire.server.common.annotation.OperationLog;
import com.hczt.fire.server.common.page.PageInfo;
import com.hczt.fire.server.common.security.FormToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Size;

/**
 * @author marvin.ma
 * @create 2017-10-18 23:00
 * @desc 角色管理
 **/
@Validated  //开启方法级别验证支持
@Controller
@RequestMapping("/sys/role")
public class SysRoleController {

    private static final Logger log = LoggerFactory.getLogger(SysRoleController.class);

    private static final String BASE_PATH = "admin/sys/";

    @Resource
    private SysRoleService sysRoleService;

    /**
     * 分页查询角色列表
     * @param pageNumber 当前页码
     * @param modelMap
     * @return
     */
    @RequiresPermissions("role:list")
    @GetMapping
    public String list(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber, ModelMap modelMap){
        log.debug("分页查询角色列表参数! pageNumber = {}, pageSize={}", pageNumber, Constant.PAGE_SIZE);
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(pageNumber);
        pageInfo.setPageSize(Constant.PAGE_SIZE);
        PagedQuery<SysRole> roles = sysRoleService.getRoleList(pageInfo);
        log.info("分页查询角色列表结果！ pageInfo = {}", roles);
        modelMap.put("pageInfo", roles);
        return BASE_PATH + "role-list";
    }

    /**
     * 跳转到角色添加页面
     * @return
     */
    @FormToken(save = true)
    @RequiresPermissions("role:create")
    @GetMapping(value = "/add")
    public String add(ModelMap modelMap){
        return BASE_PATH + "admin-role-add";
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @FormToken(remove = true)
    @OperationLog(value = "添加角色")
    @RequiresPermissions("role:create")
    @ResponseBody
    @PostMapping
    public ModelMap saveRole(@Validated({Create.class}) SysRole role){
        ModelMap messagesMap = new ModelMap();

        log.debug("添加角色参数! role = {}", role);

        //执行保存
        sysRoleService.save(role);
        log.info("添加角色成功! roleId = {}", role.getId());
        messagesMap.put("status", "success");
        messagesMap.put("message", "添加成功!");
        return messagesMap;
    }

    /**
     * 跳转到角色编辑页面
     * @return
     */
    @FormToken(save = true)
    @RequiresPermissions("role:update")
    @GetMapping(value = "/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap modelMap) throws Exception {
        log.debug("跳转到编辑角色信息页面参数! id = {}", id);
        SysRole role = sysRoleService.findById(id);

        log.info("跳转到编辑角色信息页面成功!, id = {}", id);
        modelMap.put("model", role);
        return BASE_PATH + "admin-role-edit";
    }

    /**
     * 更新角色信息
     * @param roleId
     * @param role
     * @return
     */
    @FormToken(remove = true)
    @OperationLog(value = "编辑角色")
    @RequiresPermissions("role:update")
    @ResponseBody
    @PutMapping(value = "/{roleId}")
    public ModelMap updateRole(@PathVariable("roleId") Long roleId, @Validated({Update.class}) SysRole role){
        ModelMap messagesMap = new ModelMap();

        log.debug("编辑角色参数! roleId= {}, role = {}", roleId, role);

        role.setId(roleId);
        //sysRoleService.updateSelective(role);  //TODO
        log.info("编辑角色成功! roleId= {}, role = {}", roleId, role);
        messagesMap.put("status", "success");
        messagesMap.put("message", "编辑成功!");
        return messagesMap;
    }

    /**
     * 跳转到角色授权页面
     * @param roleId
     * @return
     */
    @FormToken(save = true)
    @RequiresPermissions("role:permission")
    @GetMapping("/{roleId}/permission")
    public String toRolePermission(@PathVariable("roleId")Long roleId, ModelMap modelMap) throws Exception {

        //所有权限列表
        //List<TreeNode> treeNodeList = permissionService.findTreeList();  //TODO
        //String jsonStr = JSONUtil.toJsonStr(treeNodeList);

        //当前角色所拥有的权限ID集合
        //String permissionIds = rolePermissionService.findPermissionIdsByRoleId(roleId);  //TODO

        modelMap.put("roleId", roleId);
        //modelMap.put("treeNodeList", jsonStr);
        //modelMap.put("permissionIds", permissionIds);   //TODO
        return BASE_PATH + "admin-role-permission";
    }

    /**
     * 执行角色授权
     * @param roleId
     * @param permissionIds
     * @return
     * @throws Exception
     */
    @FormToken(remove = true)
    @OperationLog(value = "角色授权")
    @RequiresPermissions("role:permission")
    @ResponseBody
    @PutMapping("/{roleId}/permission")
    public ModelMap rolePermission(@PathVariable("roleId")Long roleId, @Size(message = "请至少选择一个", min = 1) Long[] permissionIds) throws Exception {
        ModelMap messagesMap = new ModelMap();

        //rolePermissionService.saveOrUpdate(roleId, permissionIds);  //TODO
        messagesMap.put("status", "success");
        messagesMap.put("message", "授权成功!");
        return messagesMap;
    }

    /**
     * 检验角色名是否存在
     * @param id
     * @param name
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/isExist")
    public Boolean isExist(Long id, String name){
        boolean flag = true;
        log.debug("检验角色名是否存在参数! id= {}, name= {}", id, name);
        SysRole record = sysRoleService.findByName(name);
        if (null != record && !record.getId().equals(id)) {
            flag = false;
        }
        log.debug("检验角色名是否存在结果! flag = {}", flag);
        return flag;
    }
}
